/**
 *图片上传
 *创建时间：2017-08-24
 *作者：rao.huagang
 */
(function($) {
  $.fn.simpleUploader = function(options) {
    var _this = $(this),
      uploader,
      defaults = {
        width: '1', //缩略图宽度
        height: '1', //缩略图高度
        filetype: '*', //文件类型
        required: "", //是否必填，不为空时必填
        filenum: 300, //上传文件个数
        filesize: 1024, //所有文件中大小
        singlesize: 500, //单个文件大小
        index: 0
      }
    var opts = $.extend({}, defaults, options);
    var fileName = "";
    var pick = "picker" + opts.index;
    var $isexist = _this.find("div.file-list").attr("id");
    if (typeof($isexist) == "undefined") {
      if (opts.required == "") {
        if (opts.filetype == "images") {
          _this.append('<input type="hidden" class="uploadvalid"><input type="hidden" class="required uploading" data-valid="isZero:0" data-error="图片上传中"><div id="fileList' + opts.index + '" class="file-list"><div id="' + pick + '" class="simupload"><i class="iconfont-guangming icon-shangchuan"></i></div></div>');
        } else {
          _this.append('<input type="hidden" class="uploadvalid"><input type="hidden" class="required uploading" data-valid="isZero:0" data-error="附件上传中"><div id="fileList' + opts.index + '" class="file-list"><div id="' + pick + '" class="addupload_btn simupload_file">新增附件</div></div>');

        }
      } else {
        if (opts.filetype == "images") {
          _this.append('<input type="hidden" class="required uploadvalid" data-valid="isNonEmpty" data-error="上传图片不能为空"><input type="hidden" class="required uploading" data-valid="isZero:0" data-error="图片上传中"><div id="fileList' + opts.index + '" class="file-list"><div id="' + pick + '" class="simupload"><i class="iconfont-guangming icon-shangchuan"></i></div></div>');
        } else {
          _this.append('<input type="hidden" class="required uploadvalid" data-valid="isNonEmpty" data-error="上传附件不能为空"><input type="hidden" class="required uploading" data-valid="isZero:0" data-error="附件上传中"><div id="fileList' + opts.index + '" class="file-list"><div id="' + pick + '" class="addupload_btn simupload_file">新增附件</div></div>');
        }
      }
    } else {
      if (opts.required == "") {
        _this.find("div.file-list").before('<input type="hidden" class="uploadvalid"><input type="hidden" class="required uploading" data-valid="isZero:0" data-error="附件上传中">')
      } else {
        _this.find("div.file-list").before('<input type="hidden" class="required uploadvalid" data-valid="isNonEmpty" data-error="上传文件不能为空"><input type="hidden" class="required uploading" data-valid="isZero:0" data-error="附件上传中">')
      }
      if (opts.filetype == "images") {
        _this.find("div.file-list").append('<div id="' + pick + '" class="simupload"><i class="iconfont-guangming icon-shangchuan"></i></div>');
      } else {
        _this.find("div.file-list").append('<div id="' + pick + '" class="addupload_btn simupload_file">新增附件</div>');
      }
    }
    var $list = _this.find(".file-list");
    if (opts.filetype == "images") { //上传图片
      uploader = WebUploader.create({
        auto: true, //选择文件后是否自动上传
        swf: '../../js/webuploader/Uploader.swf', // swf文件路径
        server: site.gateUrl + "/upload", // 文件接收服务端。
        pick: "#" + pick,
        dnd: '.simupload',
        paste: document.body,
        accept: {
          title: 'Images',
          extensions: 'gif,jpg,jpeg,bmp,png',
          mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
        },
        duplicate: false,
        disableGlobalDnd: true, //禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开
        fileNumLimit: opts.filenum,
        fileSizeLimit: opts.filesize * 1024 * 1024, // 1024 M
        fileSingleSizeLimit: opts.singlesize * 1024 * 1024, // 50 M
      });
      uploader.refresh();
      //在编辑情况下，判断上传文件数量是否超出限制
      var current = 0,
        doneState = 0,
        uploading = 0;
      uploader.on('beforeFileQueued', function(file) {
        current = $list.find(".file-item").length;
        current++; //加上当前上传这个文件
        if (current > opts.filenum) {
          ly.toast("上传文件数量超出限制");
          return false;
        }
        fileName = _this.find(".uploadvalid").val();
        if (fileName.indexOf(file.name) > -1) {
          ly.toast("上传文件重复");
          return false;
        }
      })
      uploader.on('error', function(code) {
        switch (code) {
          case "F_DUPLICATE":
            text = "上传文件重复";
            break;
          case 'Q_EXCEED_NUM_LIMIT':
            text = '上传文件数量超出限制';
            break;
          case 'Q_EXCEED_SIZE_LIMIT':
            text = '上传文件总大小超出限制(' + opts.filesize + "MB)";
            break;
          case 'F_EXCEED_SIZE':
            text = '上传文件大小超出限制(' + opts.singlesize + "MB)";
            break;
          case 'Q_TYPE_DENIED':
            text = '上传文件类型错误';
            break;
          default:
            text = '上传失败，请重试';
            break;
        }
        ly.toast(text);
        return false;
      });
      uploader.on('fileQueued', function(file) {
        var $li = $('<div id="' + file.id + '"class="file-item"><input type="hidden" class="filepath"><img><div class="info">' + file.name + '</div><div class="cancel"><i class="iconfont-guangming icon-shanchu1"></i></div></div>'),
          $img = $li.find('img'),
          text;
        $list.find(".simupload").before($li);
        fileName = _this.find(".uploadvalid").val();
        _this.find(".uploadvalid").removeAttr("value");
        var uploader_filename = new Array();
        if (file.name.indexOf(",") > 0) {
          var fileStr = file.name;
          file.name = fileStr.replace(/\,/g, "");
        }
        if (fileName != "") {
          fileName = fileName + "," + file.name;
        } else {
          fileName = file.name;
        }
        uploader_filename.push(fileName);

        //给隐藏信息赋值
        _this.find(".uploadvalid").val(uploader_filename);
        if (typeof(text) == "undefined") {
          // 创建缩略图
          uploader.makeThumb(file, function(error, src) {
            if (error) {
              return false;
            } else {
              doneState = $list.find(".upload-state-done").length || 0;
              uploading = parseInt(current - doneState)
              _this.find(".uploading").val(uploading);
              $("#" + file.id).css('background', "#fff url('../../img/par_15.gif') no-repeat center center");
            }
          }, opts.width, opts.height);
        }
      });
      // 文件上传成功，给item添加成功class, 用样式标记上传成功。
      uploader.on('uploadSuccess', function(file, response) {
        // console.log(response)
        var $li = $('#' + file.id),
          $success = $li.find('div.success');
        $li.addClass('upload-state-done');
        if (response.code == 1) {
          $li.removeAttr("style");
          $li.find('img').attr("src", response.msg);
          //   $li.find("input.filepath").val(response.result.filePath).attr({
          //     "fileName": response.result.fileName,
          //     "fileSize": response.result.fileSize,
          //     "fileType": 1,
          //     "businessCode": response.result.businessCode
          //   })
          $li.find("input.filepath").val(response.msg)
        }
        //避免重复创建
        if (!$success.length) {
          $success = $('<div class="success"></div>').appendTo($li);
        }
        uploading--
        _this.find(".uploading").val(uploading);
        if (uploading == 0) {
          _this.find(".uploading").val("0").blur();
        }
      });
      uploader.onError = function(code) {
        alert('Eroor: ' + code);
      };
      // 文件上传失败，显示上传出错。
      uploader.on('uploadError', function(file, response) {
        var $li = $('#' + file.id),
          $error = $li.find('div.error');
        $li.removeAttr("style").addClass("errStatus");
        // 避免重复创建
        if (!$error.length) {
          $error = $('<div class="error"></div>').appendTo($li);
        }
        $error.text('上传失败');
      });
    } else { //上传所有文件
      uploader = WebUploader.create({
        auto: true, //选择文件后是否自动上传
        swf: '../../js/webuploader/Uploader.swf', // swf文件路径
        server: site.gateUrl + "/upload", // 文件接收服务端。
        pick: "#" + pick,
        dnd: '.simupload_file',
        paste: document.body,
        duplicate: false,
        disableGlobalDnd: true, //禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开
        fileNumLimit: opts.filenum,
        fileSizeLimit: opts.filesize * 1024 * 1024, // 200 M
        fileSingleSizeLimit: opts.singlesize * 1024 * 1024, // 50 M
      });
      uploader.refresh();
      //在编辑情况下，判断上传文件数量是否超出限制
      var current = 0,
        doneState = 0,
        uploading = 0;
      uploader.on('beforeFileQueued', function(file) {
        current = $list.find(".file-item").length;
        current++; //加上当前上传这个文件
        if (current > opts.filenum) {
          ly.toast("上传文件数量超出限制");
          return false;
        }
        fileName = _this.find(".uploadvalid").val();
        if (fileName.indexOf(file.name) > -1) {
          ly.toast("上传文件重复");
          return false;
        }
      });
      uploader.on('error', function(code) {
        switch (code) {
          case "F_DUPLICATE":
            text = "上传文件重复";
            break;
          case 'Q_EXCEED_NUM_LIMIT':
            text = '上传文件数量超出限制';
            break;
          case 'Q_EXCEED_SIZE_LIMIT':
            text = '上传文件总大小超出限制(' + opts.filesize + "MB)";
            break;
          case 'F_EXCEED_SIZE':
            text = '上传文件大小超出限制(' + opts.singlesize + "MB)";
            break;
          case 'Q_TYPE_DENIED':
            text = '上传文件类型错误';
            break;
          default:
            text = '上传失败，请重试';
            break;
        }
        ly.toast(text);
        return false;
      });
      uploader.on('fileQueued', function(file) {
        var text;
        var $li = $('<div id="' + file.id + '" class="file-item annex-item"><input type="hidden" class="filepath"><div class="info" title="' + file.name + '"><i class="iconfont-guangming icon-iconfontfile"></i>附件：《' + file.name + '》</div><div class="cancel"><span>删除</span></div></div>');
        $li.find(".info").show();
        $list.find(".simupload_file").before($li);
        fileName = _this.find(".uploadvalid").val();
        _this.find(".uploadvalid").removeAttr("value");
        var uploader_filename = new Array();
        if (file.name.indexOf(",") > 0) {
          var fileStr = file.name;
          file.name = fileStr.replace(/\,/g, "");
        }
        if (fileName != "") {
          fileName = fileName + "," + file.name;
        } else {
          fileName = file.name;
        }
        uploader_filename.push(fileName);
        //给隐藏信息赋值
        _this.find(".uploadvalid").val(uploader_filename);
        //验证上传中。。。
        doneState = $list.find(".upload-state-done").length || 0;
        uploading = parseInt(current - doneState)
        _this.find(".uploading").val(uploading);
      });
      uploader.on('uploadSuccess', function(file, response) {
        // console.log(response)
        var $li = $('#' + file.id);
        $li.addClass('upload-state-done');
        var $success = $li.find('div.success');
        if (response.code == 1) {
          //   $li.find("input.filepath").val(response.result.filePath).attr({
          //     "fileName": response.result.fileName,
          //     "fileSize": response.result.fileSize,
          //     "fileType": 4,
          //     "businessCode": response.result.businessCode
          //   })
          $li.find("input.filepath").val(response.msg);
          $li.find("input.filepath").attr('fileName', file.name);
        }
        uploading--
        _this.find(".uploading").val(uploading);
        if (uploading == 0) {
          _this.find(".uploading").val("0").blur();
        }
      });
      // 文件上传失败，显示上传出错。
      uploader.on('uploadError', function(file, response) {
        var $li = $('#' + file.id),
          $error = $li.find('div.error');
        $li.find('p.state').text('上传出错');
        $li.addClass("errStatus");
        // 避免重复创建
        if (!$error.length) {
          $error = $('<div class="error"></div>').appendTo($li);
        }
        $error.css("width", $li.find('div.info').width()).text('上传失败');
      });
      uploader.on('uploadComplete', function(file) {
        $('#' + file.id).find('div.progress').fadeOut();
        $('#' + file.id).find('p.state').fadeOut(300);
      });
    }
    //删除
    _this.on('click', '.file-list .cancel', function() {
      var fileItem = $(this).parent(".file-item");
      var fname = fileItem.find(".filepath").attr("fileName");
      var fl = $(this).parents(".simple-uploader").find(".uploadvalid").val().split(",");
      fl.splice($.inArray(fname, fl), 1);
      $(this).parents(".simple-uploader").find(".uploadvalid").val(fl);
      var errStatus = $(this).parents(".file-list").find(".file-item.errStatus").length;
      errStatus--;
      if (errStatus < 0) {
        errStatus = 0;
      }
      $(this).parents(".simple-uploader").find(".uploading").val(errStatus);
      try {
        var id = $(fileItem).attr("id");
        uploader.removeFile(id, true);
      } catch (e) {}
      $(fileItem).fadeOut(function() {
        $(fileItem).remove();
      });
      if (($(fileItem).parents(".file-list").find(".file-item").length - 1) == 0) {
        $(".file-list").parent(".simple-uploader").removeClass('success tip error');
      }
    });
  };
})(jQuery);


function simpleuploader() {
  $("[type=simple-uploader]").each(function(index) {
    var _this = $(this);
    var filetype = _this.attr("filetype");
    var filesize = _this.attr("filesize");
    var singlesize = _this.attr("singlesize");
    var filenum = _this.attr("filenum");
    var required = _this.attr("required");
    _this.simpleUploader({
      filetype: filetype, //文件类型
      filenum: filenum, //上传文件个数
      filesize: filesize, //所有文件中大小
      singlesize: singlesize, //单个文件大小
      required: required, //是否验证
      index: index
    });
  });
}
simpleuploader();